<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-02-08 15:32:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-10-25 14:12:11
 * @FilePath: \zhmc_pc\sys\src\views\Asset\Pasture\Enclosure\components\components\Transfer.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { Form } from '@/components/Form'
import { reactive, ref, watch, PropType } from 'vue'
import { required } from '@/utils/formRules'
import { zcPastureListApi } from '@/api/fa/pasture'
import { ucDeptListApi } from '@/api/uc/dept'
import { spEnclosureListApi } from '@/api/fa/enclosure'
import { ucOrgDeptUserListApi } from '@/api/fa/user'
import { useCache } from '@/hooks/web/useCache'
import { useForm } from '@/hooks/web/useForm'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
const myDeptList: any = wsCache.get('myDeptList')
const myUserList: any = ref(wsCache.get('myUserList'))
console.log(myUserList.value, 'myUserList', myDeptList, 'myDeptList')
const props = defineProps({
  data: {
    type: Array, // 栏位列表
    default: () => null
  },
  dataInfo: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const rules = reactive({
  type: [required],
  date: [required],
  pasture_org_id: [required],
  admin_org_id: [required]
})

const newTreeData = ref<any[]>([])

const getEnclosure = async (val) => {
  const res = await spEnclosureListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log(res.data, 'res.data')
    newTreeData.value = [{ id: '0', name: '=== 顶级 ===' }, ...res.data]
  }
}

const data = ref<any>({})

const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])

const onCustomer = async (value) => {
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_user_id = ''
    data.value.pasture_dept_name = ''
    await DeptList(value)
  }
  await methods.setValues(data.value)
}
const DeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
}
// 管理员用户列表
const myUserListChange = async (value) => {
  console.log(value, 'value')
  myUserList.value = []
  data.value.admin_dept_id = value
  data.value.admin_user_id = ''
  data.value.admin_user_name = ''
  const parmas: any = {
    org_id: wsCache.get('userInfo').default_org_id,
    dept_id: value
  }
  const res: any = await ucOrgDeptUserListApi(parmas)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    myUserList.value = res.data
  }
}
const UserList = async (value) => {
  console.log(value, 'value')
  newUserData.value = []
  const parmas: any = {
    org_id: data.value.pasture_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi(parmas)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
  // await stateChangeUser(value)
}
const stateChangeUser = async (value) => {
  console.log(value, ' value')
}
// let state = ref(false)
const typeChange = async (value) => {
  // feedShowType.value = value
  // console.log(value, ' typeChange', schema)
  // state.value = value == 1 ? 'true' : 'false'
  data.value.type = value
  if (value == 1) {
    schema[6].hidden = true
  } else {
    schema[6].hidden = false
  }
}

const outEnclosure = async (value) => {
  data.value.in_enclosure_id = value
}
const time = async (value) => {
  data.value.date = value
  if (data.value.type == 1) {
    schema[6].hidden = true
  } else {
    schema[6].hidden = false
  }
}
const schema = reactive<FormSchema[]>([
  {
    field: 'admin_dept_id',
    label: '管理部门',
    component: 'TreeSelect',
    componentProps: {
      data: myDeptList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: myUserListChange
    }
  },
  {
    field: 'admin_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: myUserList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    componentProps: {
      options: dict.enclosure_type,
      onChange: typeChange
    }
  },
  {
    field: 'in_enclosure_id',
    label: '栏位'
    // component: 'TreeSelect',
    // hidden: false,
    // componentProps: {
    //   data: newTreeData,
    //   'check-strictly': true,
    //   'default-expand-all': true,
    //   'node-key': 'id',
    //   props: {
    //     children: 'children',
    //     label: 'name'
    //   },
    //   onChange: outEnclosure
    // }
  },
  {
    field: 'date',
    label: '时间',
    component: 'DatePicker',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      onChange: time
    }
  }
])

const { register, methods } = useForm({
  schema
})
// console.log(props.data, 'props.data')

defineExpose({
  data
  // elFormRef
})
// watch(
//   () => props.data,
//   (value) => {
//     if (!value) return
//     newTreeData.value = [{ id: '0', name: '=== 顶级 ===' }, ...value]
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
watch(
  () => props.currentRow,
  (value) => {
    if (!value) return
    data.value = props.currentRow
    if (data.value.type == 1) {
      schema[6].hidden = true
    } else {
      schema[6].hidden = false
    }
    methods.setValues(data.value)
  },
  {
    deep: true,
    immediate: true
  }
)
const init = async () => {
  console.log(props.currentRow, 'props.currentRow')
  if (props.currentRow) {
    data.value.admin_dept_id = wsCache.get('userInfo').default_dept_id
    await DeptList(props.currentRow.pasture_org_id)
    await UserList(props.currentRow.pasture_dept_id)
    await getEnclosure(props.currentRow.pasture_org_id)
  }
}
init()
</script>

<template>
  <Form @register="register" :rules="rules">
    <template #in_enclosure_id>
      <ElSelect v-model="data.in_enclosure_id" @change="outEnclosure">
        <ElOption v-for="item in newTreeData" :key="item.id" :label="item.name" :value="item.id">
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
            <ElTag :type="item.type == '1' ? 'success' : item.type == '2' ? 'warning' : 'danger'">
              {{ item.type == '1' ? '育肥' : item.type == '2' ? '低效' : '' }}
            </ElTag>
          </span>
        </ElOption>
      </ElSelect>
    </template>
  </Form>
</template>
